﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using InputParsing;

namespace DissipativeInputProcessing
{
    abstract class FramePool : IFramePool
    {
        protected InputParser _parser = InputParser.Instance;
        protected FramePalette _palette;
        // ReadOnlyCollection<IFrame> _rOFrames;

        public FramePool()
        {
            Frames = new List<IFrame>();
        }

        public FramePalette CommonPalette
        {
            get { return _palette; }
            set
            {
                _palette = value;
                foreach (var frame in Frames)
                    frame.Palette = _palette;
            }
        }

        public IList<IFrame> Frames { get; protected set; }

        
        public void Clear()
        {
            Frames.Clear();
        }

        public IFrame GetFrame(double number)
        {
            var n = (int)number;
            if (n < 0)
                n = 0;
            else if (n >= Frames.Count)
                n = Frames.Count - 1;
            return Frames[n];
        }


        public FramePalette CreatePaletteAccordingToFrame(IFrame frame)
        {
            var newPalette = new FramePalette
            {
                MaxColor = Color.White,
                MinColor = Color.Black,
                MaxValue = frame.MaxSourceValue,
                MinValue = frame.MinSourceValue
            };
            return newPalette;
        }

        public FramePalette CreateCommonPalette()
        {
            if (Frames.Count > 0)
            {
                var min = Frames[0].MinSourceValue;
                var max = Frames[0].MaxSourceValue;
                for (var i = Frames.Count; --i >= 0; )
                {
                    if (Frames[i].MaxSourceValue > max)
                        max = Frames[i].MaxSourceValue;
                    if (Frames[i].MinSourceValue < min)
                        min = Frames[i].MinSourceValue;
                }
                var newPalette = new FramePalette
                {
                    MaxColor = Color.White,
                    MinColor = Color.Black,
                    MaxValue = max,
                    MinValue = min
                };
                return newPalette;
            }
            return null;
        }
    }
}
